package bai6.com.server;

/**
 * @author nglehien
 * Oct 21, 2012 - 8:44:26 PM
 */
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import bai6.com.util.FileUtil;
import bai6.com.myfile.MyFile;

public class MyConnection extends Thread {

	private Socket socket;

	public MyConnection(Socket socket) {
		this.socket = socket;
		start();
	}

	private void convertFile() throws IOException, ClassNotFoundException {
		ObjectInputStream objectInputStream = new ObjectInputStream(
				socket.getInputStream());
		MyFile myFile = (MyFile) objectInputStream.readObject();
		String data = FileUtil.readFile(myFile.getFile()).toString();

		data = data.replaceAll(myFile.getFind(), myFile.getReplace());

		myFile.setFile(FileUtil.writeFile(data));
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(
				socket.getOutputStream());
		objectOutputStream.writeObject(myFile);

		objectInputStream.close();
		objectOutputStream.close();
		socket.close();
	}

	@Override
	public void run() {
		try {
			convertFile();
		} catch (ClassNotFoundException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.run();
	}
}
